<template >
  <div style="display: flex;flex-direction: column;align-items: center">
    <div style="width: 90%;display: flex;justify-content: space-between;padding-top: 20px;margin-bottom: 10px">
      <el-badge :value="now.taskNumber" class="item">
        <el-button size="default" round>今日记忆任务量</el-button>
      </el-badge>
      <el-badge :value="now.groupNumber" class="item">
        <el-button size="default" round>当前小组数量</el-button>
      </el-badge>
    </div>
    <div>
      <div v-if="showMemorize" style="display: flex;flex-direction: column;align-items: center">
        <div style="display: flex;flex-direction: column;align-items: center">
          <el-card shadow="always" class="card">{{word.wordstr}}</el-card>
          <el-card shadow="always" class="card" >{{word.pron}}<el-icon class="micro" @click="playAudio"><microphone /></el-icon></el-card>
          <el-card shadow="always" class="card1" style="overflow: hidden;text-wrap: none"><span>{{word.paraphrase}}</span></el-card>
          <el-card shadow="always" class="sentence" style="position: relative">
            <span style="white-space: pre">例句</span>
            <el-button type="primary" icon="ArrowLeftBold" style="position: absolute;left: 600px;top:18px" @click="prevSentence"/>
            <el-button type="primary" icon="ArrowRightBold" style="position: absolute;left: 640px;top:18px" @click="nextSentence"/>
            <br><br>
            <span style="">{{ sent.eng_sent }}</span><br><br>
            <span>{{ sent.chn_sent }}</span>
          </el-card>
        </div>
        <div class="button-box">
          <el-button type="success" size="large" round @click="yes">熟悉</el-button>
          <el-button type="warning" size="large" round @click="blur">模糊</el-button>
          <el-button type="danger" size="large" round @click="no">忘记</el-button>
        </div>
      </div>
      <div v-if="showContinue" style="height: 68vh;display: flex;flex-direction: column;align-items: center;justify-content: center;" >
        <p style="line-height: 30px;font-size: 20px;margin-bottom: 20px">{{tips}}</p>
        <el-button type="primary" size="large" round @click="continueMemorize">{{buttonTips}}</el-button>
      </div>
    </div>


    <div style="width: 100%;display: flex;justify-content: center;margin-top: 50px">
      <el-progress
          class="el-progress"
          :text-inside="true"
          :stroke-width="18"
          :percentage="percentage"
          status="success"
      />
    </div>
  </div>

</template>

<script>
import request from "@/utils/request";

function randomNum(min,max){
  parseInt(Math.random()*(max-min+1)+min,10);
  let num = Math.floor(Math.random()*(max-min+1)+min);
  return num;
}
// 入参 fmt-格式 date-日期
function dateFormat(fmt, date) {
  let ret;
  const opt = {
    "Y+": date.getFullYear().toString(),        // 年
    "m+": (date.getMonth() + 1).toString(),     // 月
    "d+": date.getDate().toString(),            // 日
    "H+": date.getHours().toString(),           // 时
    "M+": date.getMinutes().toString(),         // 分
    "S+": date.getSeconds().toString()          // 秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };
  for (let k in opt) {
    ret = new RegExp("(" + k + ")").exec(fmt);
    if (ret) {
      fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
    };
  };
  return fmt;
}

export default {
  name: "Memorize",
  data(){
    return {
      wordId:0,
      sentid:0,
      words:[],
      groupWords:[],
      groupDones:[],
      dones:0,
      allDones:0,
      word:{
        wordstr:"test",
        pron:"test",
        paraphrase:"test",
      },
      percentage:0,
      audio:new Audio(),
      wordentries:null,
      sent:{
        eng_sent:"no example sentences found.",
        chn_sent:"没有查询到例句。",
      },
      fsent:{
        eng_sent:"no example sentences found.",
        chn_sent:"没有查询到例句。",
      },
      setting:{},
      now:{},
      showMemorize:true,
      showContinue:false,
      tips:"你已经完成部分记忆",
      buttonTips:"继续记忆",
      efficiency:{
        eid:null,
        number:30,
        start_time:new Date(),
        end_time:new Date()
      }
    }
  },
  async created(){
    console.log("memorize created")
    //获取设置
    await request.get("/api/setting/get",{params:{id:1}}).then(res=>{
      console.log("Setting")
      // console.log(res)
      this.setting = res.data;
      this.now = JSON.parse(JSON.stringify(this.setting));
      this.now.taskNumber -= this.setting.todayDone;
      this.allDones = this.setting.todayDone;
      this.percentage = Math.floor((this.allDones / this.setting.taskNumber)*100)
      console.log("end????")
      console.log(this.now.taskNumber)
      console.log(this.setting.todayDone)
      if (this.setting.taskNumber === this.setting.todayDone) {
        this.showMemorize = false;
        this.showContinue = true;
        this.tips = "你已经完成今天的记忆任务！"
        this.buttonTips = "查看分析数据"
        this.percentage = 100;
        this.now.taskNumber = 0;
        this.now.groupNumber = 0;
        return
      }
      // console.log(this.setting)
    })
    //获取记忆任务
    console.log("but now setting")
    console.log(this.setting)
    request.get("/api/memorizeWord/task",{
      params:{
        taskNumber:this.setting.taskNumber,
        proportion:this.setting.proportion
      }
    }).then(res=>{
      console.log("Task")
      if (res.code === '0') {
        this.words = res.data
        this.groupWords = this.words.slice(0,this.setting.groupNumber)
        this.words = this.words.slice(this.setting.groupNumber,this.words.length)
        this.wordId = randomNum(0,this.setting.groupNumber-1);
        this.word = this.groupWords[this.wordId];
        this.efficiency.start_time = dateFormat("YYYY-mm-dd HH:MM:SS", new Date());
      }
      request.get("/sen",{
        params:{
          jsonversion:"2",
          client:"mobile",
          network:"wifi",
          xmlVersion:"5.1",
          q:this.groupWords[this.wordId].wordstr
        }
      }).then(res=>{
        //console.log(res.collins.collins_entries[0].entries.entry)
        this.wordentries = res.collins.collins_entries[0].entries.entry
        if (JSON.stringify(this.wordentries) == "{}") {
          //没有例句
          this.sent = JSON.parse(JSON.stringify(this.fsent))
          return
        }
        //有
        let sent = this.wordentries[0].tran_entry[0].exam_sents.sent[0];
        if (JSON.stringify(sent) == "{}") {
          //没有例句
          this.sent = JSON.parse(JSON.stringify(this.fsent))
          return
        }
        this.sent = JSON.parse(JSON.stringify(sent))
      })
    })

  },
  methods:{
    playAudio(){
      this.audio.src = "http://dict.youdao.com/dictvoice?audio=" + this.word.wordstr;
      this.audio.play()
    },
    reloadSentence(){
      request.get("/sen",{
        params:{
          jsonversion:"2",
          client:"mobile",
          network:"wifi",
          xmlVersion:"5.1",
          q:this.word.wordstr
        }
      }).then(res=>{
        // console.log(res.collins.collins_entries[0].entries.entry)
        this.wordentries = res.collins.collins_entries[0].entries.entry
        if (JSON.stringify(this.wordentries) == "{}") {
          //没有例句
          this.sent = JSON.parse(JSON.stringify(this.fsent))
          return
        }
        //有
        let sent = this.wordentries[0].tran_entry[0].exam_sents.sent[0];
        if (JSON.stringify(sent) == "{}") {
          //没有例句
          this.sent = JSON.parse(JSON.stringify(this.fsent))
          return
        }
        this.sent = JSON.parse(JSON.stringify(sent))
        // console.log("查询到例句")
        // console.log(this.sent)
      })
    },
    percentageFlush(remove){
      if (remove) {
        this.groupDones.push(this.groupWords[this.wordId])
        this.dones++;
        this.allDones++;
        if (this.allDones === this.setting.taskNumber) {
          this.$message.success("已经完成今日的任务。")
          this.showMemorize = false;
          this.showContinue = true;
          this.setting.todayDone += this.dones;
          request.post("/api/memorizeWord/updateLevel",this.groupDones).then(res=>{
            console.log(res)
          })
          request.post("/api/setting/update",this.setting).then(res=>{
            console.log(res)
          })
          request.post("/api/remember/insertNumber",this.setting).then(res=>{
            this.$message.success("已经添加今日记忆单词的数量到数据库中")
          })
          this.efficiency.end_time = dateFormat("YYYY-mm-dd HH:MM:SS", new Date());
          this.efficiency.number = this.dones;
          console.log(this.efficiency)
          //-------------------------------------------------
          request.get("/api/efficiency/insert",{
            params:{
              number:this.efficiency.number,
              startTime:this.efficiency.start_time,
              endTime:this.efficiency.end_time
            }
          }).then(res=>{
            console.log(res)
          })
          this.tips = "你已经完成今天的记忆任务！"
          this.buttonTips = "查看分析数据"
          this.percentage = 100;
          this.now.taskNumber = 0;
          return;
        }
        if (this.dones === this.setting.groupNumber) {
          this.$message.success("已经完成一个小组的记忆。")
          this.showMemorize = false;
          this.showContinue = true;
          console.log(this.groupDones)
          this.setting.todayDone += this.dones;
          request.post("/api/memorizeWord/updateLevel",this.groupDones).then(res=>{
            console.log(res)
          })
          request.post("/api/setting/update",this.setting).then(res=>{
            console.log(res)
          })
          this.efficiency.end_time = dateFormat("YYYY-mm-dd HH:MM:SS", new Date());
          this.efficiency.number = this.dones;
          console.log(this.efficiency)
          //-------------------------------------------------
          request.get("/api/efficiency/insert",{
            params:{
              number:this.efficiency.number,
              startTime:this.efficiency.start_time,
              endTime:this.efficiency.end_time
            }
          }).then(res=>{
            console.log(res)
          })
          this.tips = "你已经完成部分记忆"
          this.buttonTips = "继续记忆"
          return
        }
        if (this.groupWords.length>1){
          this.groupWords.splice(this.wordId,1);
        }
        // console.log(this.groupDones)
      }
      if (this.groupWords.length >= 2) {
        this.wordId = randomNum(0,this.groupWords.length-1);
      } else {
        this.wordId = 0;
      }
      this.word = this.groupWords[this.wordId];
      this.percentage = Math.floor((this.allDones / this.setting.taskNumber)*100)
    },
    updateLevel(value){
      if (!this.word.hasOwnProperty("level")) {
        this.word.level = 0;
      }
      this.word.level += value;
      if (this.word.level<=-9){
        this.now.groupNumber--;
      }
      return this.word.level;
    },
    yes(){
      console.log("wordId = "+this.wordId)
      this.updateLevel(3)
      this.percentageFlush(true)
      this.reloadSentence()
      this.now.groupNumber--;
    },
    blur(){
      let level = this.updateLevel(-1)
      if (level <= -9) {
        this.percentageFlush(true)
      } else {
        this.percentageFlush(false)
      }
      this.reloadSentence()
      //console.log(this.word)
    },
    no(){
      let level = this.updateLevel(-3)
      if (level <= -9) {
        this.percentageFlush(true)
      } else {
        this.percentageFlush(false)
      }
      this.reloadSentence()
    },
    prevSentence(){
      if (this.sentid-1 < 0) {
        return;
      }
      let sent = this.wordentries[this.sentid-1].tran_entry[0].exam_sents.sent[0];
      if (JSON.stringify(sent) == "{}") {
        //没有例句
        sent = this.wordentries[0].tran_entry[0].exam_sents.sent[0];
        if (JSON.stringify(sent) == "{}") {
          //第一句页没有
          this.sent = JSON.parse(JSON.stringify(this.fsent))
        }
        return
      }
      this.sent = sent;
      this.sentid--;
    },
    nextSentence(){
      if (this.sentid+1>=this.wordentries.length){
        return;
      }
      let sent = this.wordentries[this.sentid+1].tran_entry[0].exam_sents.sent[0];
      if (JSON.stringify(sent) == "{}") {
        //没有例句
        sent = this.wordentries[0].tran_entry[0].exam_sents.sent[0];
        if (JSON.stringify(sent) == "{}") {
          //第一句页没有
          this.sent = JSON.parse(JSON.stringify(this.fsent))
        }
        return
      }
      this.sent = sent;
      this.sentid++;
    },
    continueMemorize(){
      if ("查看分析数据" === this.buttonTips) {
        this.$router.push("/remember")
      } else {
        this.showContinue = false
        this.showMemorize = true
        this.now.taskNumber -= this.setting.groupNumber;
        this.now.groupNumber = this.setting.groupNumber;
        this.groupWords = this.words.slice(0,this.setting.groupNumber)
        this.words = this.words.slice(this.setting.groupNumber,this.words.length)
        this.wordId = randomNum(0,this.setting.groupNumber-1);
        this.dones = 0;
        this.word = this.groupWords[this.wordId];
        this.efficiency.start_time = dateFormat("YYYY-mm-dd HH:MM:SS", new Date());
      }

    }
  }
}
</script>

<style scoped>
  .button-box{
    width: 90vh;
    margin-top: 20px;
    overflow: hidden;
    /*border: 1px red solid;*/
    display: flex;
    flex-direction: row;
    justify-content: space-between;
  }
  .button-box .el-button{
    width: 120px;
    font-size: 18px;
  }
  .el-card {
    width: 300px;
    height: 55px;
    margin: 10px;
    font-size: 20px;
    padding: 0px;
    text-align: center;
    border-radius: 30px;
    line-height: 15px;
  }
  .card{
    width: 80vh;
  }
  .card1{
    width: 100vh;
  }
  .sentence {
    width: 120vh;
    height: 20vh;
  }
  .el-progress{
    width: 80%;
  }
  .micro{
    color: blue;
    margin-left: 8px;
  }
</style>
